package com.sluggard.security.core.manage;

import com.sluggard.security.manage.model.vo.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Set;
import java.util.stream.Collectors;

import static com.sluggard.security.core.consts.SecurityConstant.ROLE_PREFIX;

public class SecurityUserManage {

    public static Set<GrantedAuthority> getPermissions() {
        SecurityUser userInfo = getUserInfo();
        return userInfo.getAuthorities().stream().filter(item -> !StringUtils.startsWith(item.getAuthority(), ROLE_PREFIX)).collect(Collectors.toSet());
    }

    public static Set<GrantedAuthority> getRoles() {
        SecurityUser userInfo = getUserInfo();
        return userInfo.getAuthorities().stream().filter(item -> StringUtils.startsWith(item.getAuthority(), ROLE_PREFIX)).collect(Collectors.toSet());
    }

    public static SecurityUser getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (SecurityUser) authentication.getPrincipal();
    }

}
